package top.jfunc.common.thread.monitor.change;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * j.u.c {@link ThreadPoolExecutor}适配器
 */
public class ThreadPoolExecutorParamChangeAdapter implements ParamChangeable{
	private final ThreadPoolExecutor delegate;

	public ThreadPoolExecutorParamChangeAdapter(ThreadPoolExecutor threadPoolExecutor) {
		this.delegate = threadPoolExecutor;
	}

	@Override
	public int getCorePoolSize() {
		return this.delegate.getCorePoolSize();
	}

	@Override
	public void setCorePoolSize(int corePoolSize) {
		this.delegate.setCorePoolSize(corePoolSize);
	}

	@Override
	public int getMaximumPoolSize() {
		return this.delegate.getMaximumPoolSize();
	}

	@Override
	public void setMaximumPoolSize(int maximumPoolSize) {
		this.delegate.setMaximumPoolSize(maximumPoolSize);
	}

	@Override
	public long getKeepAliveTime(TimeUnit timeUnit) {
		return this.delegate.getKeepAliveTime(timeUnit);
	}

	@Override
	public void setKeepAliveTime(long keepAliveTime, TimeUnit timeUnit) {
		this.delegate.setKeepAliveTime(keepAliveTime, timeUnit);
	}

	@Override
	public boolean allowsCoreThreadTimeOut() {
		return this.delegate.allowsCoreThreadTimeOut();
	}

	@Override
	public void allowCoreThreadTimeOut(boolean allowCoreThreadTimeOut) {
		this.delegate.allowCoreThreadTimeOut(allowCoreThreadTimeOut);
	}

	@Override
	public void setCapacity(int queueCapacity) {
		//队列容量
		BlockingQueue<Runnable> blockingQueue = this.delegate.getQueue();
		if(blockingQueue instanceof ResizableCapacityLinkedBlockingQueue){
			int capacity = ((ResizableCapacityLinkedBlockingQueue<Runnable>) blockingQueue).getCapacity();
			if(capacity != queueCapacity){
				((ResizableCapacityLinkedBlockingQueue<?>)blockingQueue).setCapacity(queueCapacity);
			}
		}
	}
}
